import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/widget/common_app_bar.dart';

import 'package:casdon/core/extentions/string_validation.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/lifeCircle/data/api/life_topic_comment_list_api.dart';
import 'package:casdon/modules/lifeCircle/domain/states/life_topic_comment_list_state.dart';
import 'package:casdon/modules/lifeCircle/data/repository/life_repository_impl.dart';
import 'package:casdon/core/network/api_client_provider.dart';
import 'package:casdon/modules/lifeCircle/providers/life_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

@RoutePage()
class ReplyListScreen extends ConsumerStatefulWidget {
  final String rootUserName;
  final String commentId;
  final String rootUserId;

  const ReplyListScreen({
    super.key,
    required this.rootUserName,
    required this.commentId,
    required this.rootUserId,
  });

  @override
  ConsumerState<ReplyListScreen> createState() => _ReplyListScreenState();
}

class _ReplyListScreenState extends ConsumerState<ReplyListScreen> {
  late Future<void> _loader;
  List<_FlatReply>? _replies;
  String? _error;
  late String _replyHint;
  late String _replyingCommentId;
  String? _replyingUserName;
  String? _replyingToUserId;
  String? _topicId;
  final _replyController = TextEditingController();
  final _replyFocusNode = FocusNode();
  bool _isSending = false;

  @override
  void initState() {
    super.initState();
    _replyingCommentId = widget.commentId;
    _replyingUserName = widget.rootUserName;
    _replyHint = '回复 ${_replyingUserName}';
    _loader = _loadReplies();
  }

  @override
  void dispose() {
    _replyController.dispose();
    _replyFocusNode.dispose();
    super.dispose();
  }

  Future<void> _loadReplies() async {
    setState(() {
      _error = null;
    });
    try {
      final usecase = ref.read(lifeCommentReplyUsecaseProvider);
      final res = await usecase.execute(
        commentId: widget.commentId,
        pageNum: 1,
        pageSize: 100,
      );
      final nested = res
          .map(
            (e) => LifeTopicCommentViewData.fromApi(TopicComment.fromJson(e)),
          )
          .toList();
      _replies = _flattenReplies(nested);
      if (_replies!.isNotEmpty) {
        _topicId = _replies!.first.data.topicId;
      }
    } catch (e) {
      _error = '加载失败';
    } finally {
      if (mounted) {
        setState(() {});
      }
    }
  }

  List<_FlatReply> _flattenReplies(List<LifeTopicCommentViewData> list) {
    final result = <_FlatReply>[];
    void walk(
      List<LifeTopicCommentViewData> nodes,
      int depth,
      String? parentUserName,
    ) {
      for (final n in nodes) {
        result.add(
          _FlatReply(data: n, depth: depth, parentUserName: parentUserName),
        );
        if (n.replies.isNotEmpty) {
          walk(n.replies, depth + 1, n.userName);
        }
      }
    }

    walk(list, 0, null);
    return result;
  }

  void _resetReplyTarget() {
    _replyingCommentId = widget.commentId;
    _replyingUserName = widget.rootUserName;
    _replyingToUserId = null;
    _replyHint = '回复 ${_replyingUserName}';
  }

  void _selectReplyTarget(_FlatReply reply) {
    _replyingCommentId = reply.data.id;
    _replyingUserName = reply.data.userName;
    _replyingToUserId = reply.data.userId;
    _replyHint = '回复 ${reply.data.userName}';
    _replyFocusNode.requestFocus();
    setState(() {});
  }

  Future<void> _submitReply() async {
    final content = _replyController.text.trim();
    if (content.isEmpty) {
      ToastUtil.show('请输入回复内容');
      return;
    }
    final topicId = _topicId;
    if (topicId == null || topicId.isEmpty) {
      ToastUtil.show('获取话题信息失败');
      return;
    }
    if (_isSending) return;

    setState(() {
      _isSending = true;
    });

    FocusScope.of(context).unfocus();
    try {
      await ref
          .read(lifeTopicAddCommentUsecaseProvider)
          .execute(
            topicId: topicId,
            content: content,
            parentId: _replyingCommentId,
            toUserId: _replyingToUserId ?? widget.rootUserId,
          );
      _replyController.clear();
      _resetReplyTarget();
      ToastUtil.show('回复成功');
      await _loadReplies();
    } catch (e) {
      ToastUtil.show('回复失败');
    } finally {
      if (mounted) {
        setState(() {
          _isSending = false;
        });
      }
    }
  }

  Future<void> _toggleLike(int index) async {
    if (_replies == null || index < 0 || index >= _replies!.length) return;
    final current = _replies![index];
    final newLiked = !current.data.isLiked;
    final newCount = newLiked
        ? current.data.likeCount + 1
        : (current.data.likeCount > 0 ? current.data.likeCount - 1 : 0);
    setState(() {
      _replies![index] = current.copyWith(
        data: current.data.copyWith(isLiked: newLiked, likeCount: newCount),
      );
    });

    try {
      final repo = LifeRepositoryImpl(apiClient: ref.read(apiClientProvider));
      await repo.likeTopic(
        id: current.data.id,
        type: 1,
        flag: newLiked ? 1 : 0,
      );
    } catch (_) {
      setState(() {
        _replies![index] = current;
      });
    }
  }

  void _deleteReply(int index) {
    if (_replies == null || index < 0 || index >= _replies!.length) return;
    final reply = _replies![index];
    setState(() {
      _replies!.removeAt(index);
    });
    ref.read(lifeDelCommentUsecaseProvider).execute(id: reply.data.id).then(
      (_) => ToastUtil.show('已删除'),
    ).catchError((_) {
      // 如果删除失败，可以考虑重新插入，简单提示即可
      ToastUtil.show('删除失败');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonAppBar(title: '${_replies?.length ?? 0} 个回复'),
      backgroundColor: Colors.white,
      body: FutureBuilder<void>(
        future: _loader,
        builder: (context, snapshot) {
          if (_replies == null &&
              snapshot.connectionState != ConnectionState.done) {
            return const Center(child: CircularProgressIndicator());
          }
          if (_error != null) {
            return Center(child: Text(_error!));
          }
          final replies = _replies ?? const <_FlatReply>[];
          return Column(
            children: [
              Expanded(
                child: ListView.separated(
                  padding: EdgeInsets.symmetric(vertical: 8.h),
                  itemBuilder: (context, index) {
                    final reply = replies[index];
                    return GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () => _selectReplyTarget(reply),
                      child: _ReplyTile(
                        reply: reply,
                        onLikeTap: () => _toggleLike(index),
                        onDeleteTap: () => _deleteReply(index),
                      ),
                    );
                  },
                  separatorBuilder: (_, __) => Divider(
                    height: 1,
                    color:
                        context.customColorThemeNonNull.gray1 ??
                        Colors.grey.shade200,
                  ),
                  itemCount: replies.length,
                ),
              ),
              SafeArea(
                child: Padding(
                  padding: EdgeInsets.all(12.w),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Expanded(
                            child: Container(
                              decoration: BoxDecoration(
                                color:
                                    (context.customColorThemeNonNull.gray1 ??
                                            Colors.grey.shade100)
                                        .withOpacity(0.6),
                                borderRadius: BorderRadius.circular(20.r),
                                border: Border.all(
                                  color: context.customColorThemeNonNull.gray2!,
                                  width: 1,
                                ),
                              ),
                              padding: EdgeInsets.symmetric(
                                horizontal: 12.w,
                                vertical: 8.h,
                              ),
                              child: TextField(
                                controller: _replyController,
                                focusNode: _replyFocusNode,
                                enabled: !_isSending,
                                decoration: InputDecoration(
                                  hintText: _replyHint,
                                  hintStyle: context.textTheme.bodyMedium
                                      ?.copyWith(
                                        color: context
                                            .customColorThemeNonNull
                                            .gray6,

                                        fontSize: 14.r,
                                      ),
                                  border: InputBorder.none,
                                  isDense: true,
                                  contentPadding: EdgeInsets.zero,
                                ),
                                style: context.textTheme.bodyMedium?.copyWith(
                                  fontSize: 14.r,
                                  color: context
                                      .customColorThemeNonNull
                                      .textColor1,
                                ),
                                textInputAction: TextInputAction.send,
                                onSubmitted: (_) => _submitReply(),
                              ),
                            ),
                          ),
                          SizedBox(width: 12.w),
                          TextButton(
                            onPressed: _isSending ? null : _submitReply,
                            child: _isSending
                                ? SizedBox(
                                    width: 16.w,
                                    height: 16.w,
                                    child: const CircularProgressIndicator(
                                      strokeWidth: 2,
                                    ),
                                  )
                                : Text(
                                    '发送',
                                    style: context.textTheme.bodyMedium
                                        ?.copyWith(
                                          color: context.colorScheme.primary,
                                        ),
                                  ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}

class _ReplyTile extends StatelessWidget {
  final _FlatReply reply;
  final VoidCallback? onLikeTap;
  final VoidCallback? onDeleteTap;

  const _ReplyTile({required this.reply, this.onLikeTap, this.onDeleteTap});

  @override
  Widget build(BuildContext context) {
    final customColors = context.customColorThemeNonNull;
    final data = reply.data;
    final avatar = data.avatarUrl.isEmpty || data.avatarUrl.isUrl() == false
        ? AssetImage(Assets.images.icAvatar.path)
        : NetworkImage(data.avatarUrl) as ImageProvider;
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          CircleAvatar(radius: 18.w, backgroundImage: avatar),
          SizedBox(width: 12.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  data.userName,
                  style: context.textTheme.bodyMedium?.copyWith(
                    color: customColors.textColor1,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                SizedBox(height: 4.h),
                Text(
                  data.displayTime,
                  style: context.textTheme.bodySmall?.copyWith(
                    color: customColors.textColor2,
                  ),
                ),
                SizedBox(height: 6.h),
                Text(
                  reply.depth == 0 || reply.parentUserName == null
                      ? data.content
                      : '回复 @${reply.parentUserName}：${data.content}',
                  style: context.textTheme.bodyMedium?.copyWith(
                    color: customColors.textColor1,
                  ),
                ),
              ],
            ),
          ),
          SizedBox(width: 8.w),
          Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              InkWell(
                onTap: onLikeTap,
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Image.asset(
                      data.isLiked
                          ? Assets.images.icZaned.path
                          : Assets.images.icZan.path,
                      width: 18.w,
                      height: 18.w,
                    ),
                    SizedBox(width: 4.w),
                    Text(
                      data.likeCount.toString(),
                      style: context.textTheme.bodySmall?.copyWith(
                        color: customColors.textColor2,
                      ),
                    ),
                  ],
                ),
              ),
              if (data.isMine) ...[
                SizedBox(width: 12.w),
                TextButton(
                  style: TextButton.styleFrom(
                    padding: EdgeInsets.zero,
                    minimumSize: Size(40.w, 24.h),
                    tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  ),
                  onPressed: onDeleteTap,
                  child: Text(
                    '删除',
                    style: context.textTheme.bodySmall?.copyWith(
                      color: onDeleteTap == null
                          ? (customColors.gray2 ?? Colors.grey)
                          : context.colorScheme.primary,
                    ),
                  ),
                ),
              ],
            ],
          ),
        ],
      ),
    );
  }
}

class _FlatReply {
  final LifeTopicCommentViewData data;
  final int depth;
  final String? parentUserName;

  _FlatReply({
    required this.data,
    required this.depth,
    required this.parentUserName,
  });

  _FlatReply copyWith({
    LifeTopicCommentViewData? data,
    int? depth,
    String? parentUserName,
  }) {
    return _FlatReply(
      data: data ?? this.data,
      depth: depth ?? this.depth,
      parentUserName: parentUserName ?? this.parentUserName,
    );
  }
}
